package com.example.newinfinity.View.PencilPicker

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Paint.Style
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.example.newinfinity.MyViewModel.DrawViewModel
import com.example.newinfinity.databinding.PalettePickerViewBinding

/*包裹调节画笔粗细和填充状态的XML视图*/
class PencilPickerView(context: Context, attrs: AttributeSet? = null) :
    FrameLayout(context, attrs) {
    private var pencilPickerViewBinding: PalettePickerViewBinding? = null

    //计算dot_fill到dot_empty的距离，用于获取填充状态改变动画的移动距离
    private val mMoveDistance: Float by lazy {
        (pencilPickerViewBinding!!.pencilDotEmpty.top - pencilPickerViewBinding!!.pencilDotFill.top).toFloat()
    }

    //点击修改系统填充状态的动画
    //修改为fill填充状态时的动画
    private val fillAnim: ObjectAnimator by lazy {  //懒加载确保mBinding!!.dotEmpty.translationY在使用时已正确初始化
        ObjectAnimator.ofFloat(
            pencilPickerViewBinding!!.pencilDotBg,
            "translationY",
            mMoveDistance, 0f
        ).apply {
            duration = 160
        }
    }

    //修改为empty空心状态时的动画
    private val emptyAnim: ObjectAnimator by lazy {
        ObjectAnimator.ofFloat(
            pencilPickerViewBinding!!.pencilDotBg,
            "translationY",
            0f, mMoveDistance
        ).apply {
            duration = 160
        }
    }

    init {
        pencilPickerViewBinding = PalettePickerViewBinding.inflate(LayoutInflater.from(context))
        val lp = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        lp.gravity = Gravity.CENTER
        addView(pencilPickerViewBinding!!.root, lp)

        //接收seekbar中实时的进度数据值
        pencilPickerViewBinding!!.pencilSeekbar.progressCallback = { progress ->
            pencilPickerViewBinding!!.pencilShowText.text = progress.toString()
            //同步修改外部绘制图形的画笔粗细和橡皮擦的粗细
            DrawViewModel.getDrawViewModel().mStrokeWidth = progress.toFloat()
            DrawViewModel.getDrawViewModel().eraserStrokeWidth = progress.toFloat()
        }

        //画笔填充状态动画与修改
        //点击修改为empty填充状态
        pencilPickerViewBinding!!.pencilDotEmpty.setOnClickListener {
            emptyAnim.start()
            //同步修改外部绘制图形的style
            DrawViewModel.getDrawViewModel().mStyle = Style.STROKE
        }
        //点击修改为fill填充状态
        pencilPickerViewBinding!!.pencilDotFill.setOnClickListener {
            fillAnim.start()
            //同步修改外部绘制图形的style
            DrawViewModel.getDrawViewModel().mStyle = Style.FILL
        }
    }

}